TWB.New_Module({
	///////////////////////////
	name : "CloseVillages",	 //
	author : "enduo",        //
	version : 1.0,           //
	///////////////////////////
	
	settings : {
		closevilnum : {
			type : "text",
			maxlength : 2
		}
	},
	ClearAll : function(){
		var V=TWB.gei("TWB-CloseVillageList");
		var i;
		for(i=V.childNodes.length-1; i>=0; i--){
			V.removeChild(V.childNodes[i]);
		}
	},
	NewClose : function(village){
		var V=TWB.gei("TWB-CloseVillageList");
		var E=TWB.dce("menuitem");
		var prop;
		for(prop in village){
			E.setAttribute(prop,village[prop]);
		}
		E.setAttribute("oncommand","TWB.Modules.Villages.ClickVil(this);");
		V.appendChild(E);
	},
	UpdateList : function(){
		if(!TWB.logged()){
			return;
		}
		
		var i;
		TWB.Modules.CloseVillages.ClearAll();
		var set=TWB.get_var("closevilnum",TWB.DEFAULTS["closevilnum"]);
		var closest=[];
		var V=TWB.gei("TWB-VillageList");
		if(TWB.Modules.Icons.Screen()=="info_village"){
			var target=TWB.Xpath("//*[@id='content_value']//tr/td/table[@class='vis']//tr[2]/td[2]",9).innerHTML.split("|");
		}
		else{
			var WN=TWB._window();
			if(typeof WN.wrappedJSObject!="undefined"){
				WN=WN.wrappedJSObject;
			}
			var target=WN.game_data.village.coord.split("|")
		}
		for(i=0; i<V.childNodes.length; i++){
			var xy=V.childNodes[i].getAttribute("value").match(/\d+\|\d+/)[0].split("|");
			var letc=Math.sqrt(Math.pow(xy[0]-target[0],2)+Math.pow(xy[1]-target[1],2));
			closest.push([letc/10000,V.childNodes[i].getAttribute("id")]);
		}
		closest.sort();
		var J=closest.length;
		J=(J>=set)?set:J;
		for(i=0; i<J; i++){
			// populate
			TWB.Modules.CloseVillages.NewClose({
				id : "TWB-c"+TWB.gei(closest[i][1]).getAttribute("id").split("TWB-v")[1],
				label : TWB.gei(closest[i][1]).getAttribute("label"),
				tooltiptext : TWB.gei(closest[i][1]).getAttribute("tooltiptext")
			});
			TWB.gei(TWB.gei(closest[i][1]).getAttribute("id").replace("v","c")).style.color=TWB.gei(closest[i][1]).style.color;
		}
	},
	
	priority : 501,
	init : function(){
		TWB.Processor.start("close_villages","Modules.CloseVillages.UpdateList","*",false);
	}
});
